﻿/*-------------------------------------------------------------------------
* 命名空间: SiliconSelect.PlcComunication/PlcCommunication
* 类       名: PlcCommunication
* 功      能:  PLC通信类,设置为单例模式.
* 时      间:  2023/7/27 13:58:55
* 版      本:  V1.0
* 作      者:  Fioman
* 格      言:  Talk is cheap,show me the code ^_^
*-------------------------------------------------------------------------*/
using SiliconSelect.BLL;
using SiliconSelect.Common;
using SiliconSelect.PlcComunication.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using HslCommunication.Profinet.Omron;
using System.Runtime.CompilerServices;
using HslCommunication;
using System.Windows.Threading;
using System.Windows;
using System.Net.Http.Headers;
using DocumentFormat.OpenXml.Vml;
using OfficeOpenXml.Sorting;
using System.Security.Principal;
using HslCommunication.Core.Net;
using OfficeOpenXml.Style.Dxf;
using SiliconSelect.Models;
using DocumentFormat.OpenXml.Office2016.Drawing.ChartDrawing;
using SiliconSelect.Base;
using TwinCAT.Ads;
using System.Reflection.Metadata;
using DocumentFormat.OpenXml.Drawing;
/*
* 目前的数据类型对应是:
* Plc心跳  UINT -> ushort  D1     3s内变化 0-1 或者 1-0   pc心跳  UINT D0 3s内变化 0-1 或者 1-0
* 设备状态  Uint-> ushort  D3   0: 自动运行 1: 待机 2: 正常停机 3: 故障停机 4: 待料 5: 满料  
* PC状态  Uint->ushort D2   1: 运行  2: 停止 3: 出错
* 已经停机时间: Uint -> ushort D4
* 
* 测试电阻工位  
* 触发测试 Uint D100       测试反馈 UINT-> ushort  D101
* 电阻率对应流水号  UINT D120   
*                       
* 分选:
* 触发分选 Uint D110
* 分选地址 Uint D111
* 分选流水号 Uint D121
*/
namespace SiliconSelect.PlcComunication
{
    public class PlcCommunication
    {
        public PlcStateModel PlcState { get; set; }
        public AdsClient NetClient;
        private static PlcCommunication? _instance;
        private static readonly object _lock = new object();

        /// <summary>
        /// 分选统计,用来决定放到写入位置.
        /// </summary>
        public int SelectedIndex { get; set; }

        /// <summary>
        /// 流水号数据写入队列
        /// </summary>
        public readonly string[] WaferAddresList = { "D300", "D302", "D304", "D306", "D308", "D310", "D312", "D314", "D316", "D318" };
        //public readonly string[] WaferAddresList = { "D0", "D0", "D0", "D0", "D0" };


        /// <summary>
        /// 
        /// </summary>
        public readonly string[] BoxNumberAddressList = { "D310", "D311", "D312", "D313", "D314" };
        //public readonly string[] BoxNumberAddressList = { "D1", "D1", "D1", "D1", "D1" };


        public int DisconnectedCount = 0;

        private PlcCommunication()
        {
            PlcState = new PlcStateModel();
            PlcState.Ip = "5.125.213.151.1.1";
            PlcState.Port = 851;
            PlcState.IsOnline = "已断开";
            NetClient = new AdsClient();
            //NetClient.ConnectTimeOut = 100; // 连接超时时间为1秒
            SelectedIndex = 1;
        }
        public static PlcCommunication Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new PlcCommunication();
                        }
                    }
                }
                return _instance;
            }
        }


        public DataResult ConnectPlc()
        {
            DataResult result = new DataResult();
            try
            {
                NetClient.Connect(PlcState.Ip!, PlcState.Port);
                if (!NetClient.IsConnected)
                {
                    result.Message = "连接失败,PLC未连接成功";
                    Application.Current?.Dispatcher.Invoke(() =>
                    {
                        PlcState.IsOnline = "已断开";
                    });
                }
                else
                {
                    result.State = true;
                    Application.Current?.Dispatcher.Invoke(() =>
                    {
                        PlcState.IsOnline = "已连接";
                        DisconnectedCount = 0;
                        // 设置电阻率对应流水号为0
                        ResetResistivityWaferId();
                    });

                    // 连接成功之后,设置PLC各种参数
                    //SetPlcParams();

                    // 每次连接成功之后,先给心跳信号写入为0.
                    //ushort pcToPlcHeartVal = 0;
                    //DataResult res = WriteToPlcHeartVal(pcToPlcHeartVal);
                    //if (!res.State)
                    //{
                    //    LogHelper.WriteLog(LogType.Warn, $"心跳写入失败: {res.Message}");
                    //}
                    //// 读取心跳
                    //DataResult<ushort> res2 = GetPlcHeartVal();
                    //if (!res2.State)
                    //{
                    //    LogHelper.WriteLog(LogType.Warn, $"PLC心跳读取失败: {res.Message}");
                    //}
                    //PlcState.LastReadHeartVal = res2.Data!;
                }
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 设置PLC各种参数.
        /// </summary>
        private void SetPlcParams()
        {
            try
            {
                // 1. 设置料盒最大数量
                var boxStateRes = LocalDataAccess.GetBoxesStates();
                if (!boxStateRes.State)
                {
                    LogHelper.WriteLog(LogType.Exception, boxStateRes.Message);
                    MessageBox.Show($"数据库操作异常: {boxStateRes.Message}", "数据库操作异常提示框", MessageBoxButton.OK, MessageBoxImage.Error);
                    Application.Current.Shutdown();
                }
                List<ushort> boxMaxCountList = new List<ushort>() { 1 };
                foreach (var box in boxStateRes.Data!)
                {
                    boxMaxCountList.Add(ushort.Parse(box.CountMax!));
                }
                DataResult plcRes = WriteBoxMaxNumberToPLc(boxMaxCountList.ToArray());
                if (!plcRes.State)
                {
                    LogHelper.WriteLog(LogType.Fatal, $"料盒最大数量写入失败,PLC通信异常: {plcRes.Message}");
                    MessageBox.Show($"PLC通信异常: {plcRes.Message}", "PLC通信异常提示框", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(LogType.Exception, ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!));
            }
        }

        /// <summary>
        /// 将料盒设定最大值写入到PLC中
        /// </summary>
        /// <param name="boxMaxCountList"></param>
        /// <returns></returns>
        public DataResult WriteBoxMaxNumberToPLc(ushort[] boxMaxCountArray)
        {
            string plcPos = "D250";
            DataResult result = new DataResult();
            //try
            //{
            //    OperateResult res = NetClient.Write(plcPos, boxMaxCountArray);
            //    if (!res.IsSuccess)
            //    {
            //        result.Message = res.Message;
            //    }
            //    else
            //    {
            //        result.State = true;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            //}
            return result;
        }

        /// <summary>
        /// 获取电阻率读取流水号触发信号.
        /// D100 读取的值是0或者1,如果是1表示触发成功.
        /// </summary>
        /// <returns></returns>
        //public DataResult<ushort> GetResistivityTriggerState()
        //{
        //    string plcPos = "D60";
        //    DataResult<ushort> result = new DataResult<ushort>();
        //    try
        //    {
        //        OperateResult<ushort> res = NetClient.ReadUInt16(plcPos);
        //        if (res.IsSuccess)
        //        {
        //            result.State = true;
        //            result.Data = res.Content;
        //        }
        //        else
        //        {
        //            result.Message = res.Message;
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
        //    }
        //    return result;
        //}

        /// <summary>
        /// 电阻率触发反馈信号,读取位置是D101
        /// </summary>
        /// <returns></returns>
        //public DataResult ClearResistivityTriggerState()
        //{
        //    string plcPos = "D60";
        //    DataResult result = new DataResult();
        //    try
        //    {
        //        OperateResult res = NetClient.Write(plcPos, (ushort)0);
        //        if (!res.IsSuccess)
        //        {
        //            result.Message = res.Message;
        //        }
        //        else
        //        {
        //            result.State = true;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
        //    }
        //    return result;
        //}

        /// <summary>
        /// 获取电阻率测试的流水号 Global_ID.IDSend2  :DINT
        /// </summary>
        /// <returns></returns>
        public DataResult<int> GetWaferIdForResistivity()
        {
            string plcPos = "Global_ID.IDSend2";
            DataResult<int> result = new DataResult<int>();
            try
            {
                return ReadDInt32Bit(plcPos);
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 重置电阻率流水号为0
        /// </summary>
        /// <returns></returns>
        public DataResult ResetResistivityWaferId(int resetVal = 0)
        {
            string plcPos = "Global_ID.IDSend2";
            DataResult result = new DataResult();
            try
            {
                return WriteDInt32Bit(plcPos, resetVal);
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }


        /// <summary>
        /// 获取触发分选的信号
        /// </summary>
        /// <returns></returns>
        public DataResult<string> GetSelectedSignal()
        {
            string plcPos = "D110";
            DataResult<string> result = new DataResult<string>();
            try
            {
                //ushort res = NetClient.ReadUInt16(plcPos).Content;
                //result.Data = res.ToString();
                //result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 获取触发分选流水号
        /// </summary>
        /// <returns></returns>
        public DataResult<string> GetSelectedWaferId()
        {
            string plcPos = "D121";
            DataResult<string> result = new DataResult<string>();
            try
            {
                //ushort res = NetClient.ReadUInt16(plcPos).Content;
                //result.Data = res.ToString();
                //result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 向Plc写入心跳信号 0-1 变化(3秒以内)
        /// </summary>
        /// <returns></returns>
        //public DataResult WriteToPlcHeartVal(ushort heartVal)
        //{
        //    string plcPos = "D0";
        //    DataResult result = new DataResult();
        //    try
        //    {
        //        OperateResult res = NetClient.Write(plcPos, heartVal);
        //        if (!res.IsSuccess)
        //        {
        //            result.Message = res.Message;
        //        }
        //        else
        //        {
        //            result.State = true;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
        //    }
        //    return result;
        //}


        /// <summary>
        /// 通知PLC服务重启.
        /// D10: 尺寸
        /// D11: 左崩
        /// D12: 右崩
        /// D13: 前崩
        /// D14: 3D
        /// D15: 下脏污
        /// D16: 上脏污
        /// D17: 隐裂
        /// D18: 后崩
        /// </summary>
        /// <param name="clientName"></param>
        /// <returns></returns>
        public DataResult RestartPlcServerByClientName(string? clientName)
        {
            DataResult result = new DataResult();
            string? plcPos = null;
            ushort plcVal = 1;
            try
            {
                //switch (clientName)
                //{
                //    case "尺寸":
                //        plcPos = "D120";
                //        break;
                //    case "左崩":
                //        plcPos = "D121";
                //        break;
                //    case "右崩":
                //        plcPos = "D122";
                //        break;
                //    case "前崩":
                //        plcPos = "D126";
                //        break;
                //    case "3D":
                //        plcPos = "D123";
                //        break;
                //    case "下脏污":
                //        plcPos = "D124";
                //        break;
                //    case "上脏污":
                //        plcPos = "D125";
                //        break;
                //    case "隐裂":
                //        plcPos = "D128";
                //        break;
                //    case "后崩":
                //        plcPos = "D127";
                //        break;
                //    default:
                //        break;
                //}
                //OperateResult resOp = NetClient.Write(plcPos, plcVal);
                //if (!resOp.IsSuccess)
                //{
                //    result.Message = result.Message;
                //}
                //else
                //{
                //    result.State = true;
                //}
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
                return result;
            }
            return result;
        }

        /// <summary>
        /// 获取料盒的数量,从PLC那边获取.
        /// D21 - D39 一共19个
        /// </summary>
        /// <returns></returns>
        public DataResult<List<ushort>> GetBoxCountsFromPlc()
        {
            string plcStartPos = "D201";
            //string plcStartPos = "D200";
            ushort count = 37;
            DataResult<List<ushort>> result = new DataResult<List<ushort>>();
            //try
            //{
            //    OperateResult<ushort[]> opRes = NetClient.ReadUInt16(plcStartPos, count);
            //    if (opRes.IsSuccess)
            //    {
            //        result.State = true;
            //        result.Data = opRes.Content.ToList();
            //    }
            //    else
            //    {
            //        result.Message = opRes.Message;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            //    return result;
            //}
            return result;
        }

        /// <summary>
        ///  清空单个料盒逻辑
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        public DataResult ClearOneBox(int val)
        {
            DataResult result = new DataResult();
            string? plcPos = "D200";
            ushort plcVal = (ushort)val;
            try
            {
                //    OperateResult resOp = NetClient.Write(plcPos, plcVal);
                //    if (!resOp.IsSuccess)
                //    {
                //        result.Message = result.Message;
                //    }
                //    else
                //    {
                //        result.State = true;
                //    }
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
                return result;
            }
            return result;
        }

        /// <summary>
        /// 写入2表示清空.
        /// </summary>
        /// <returns></returns>
        internal DataResult ClearSelectedSignal()
        {
            string plcPos = "D110";
            ushort plcVal = 0;
            DataResult result = new DataResult();
            try
            {
                //OperateResult resOp = NetClient.Write(plcPos, plcVal);
                //if (!resOp.IsSuccess)
                //{
                //    result.Message = result.Message;
                //}
                //else
                //{
                //    result.State = true;
                //}
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
                return result;
            }
            return result;
        }


        internal DataResult WriteBoxNumber(int waferId, int boxNumber)
        {

            DataResult result = new DataResult();

            try
            {
                string plcPos = $"Global_ID.PC_Data";
                int indexStart = SelectedIndex;
                int[] writeVal = new int[] { waferId, boxNumber };
                if (SelectedIndex >= 9)
                {
                    SelectedIndex = 1;
                }
                else
                {
                    SelectedIndex += 2;
                }
                return WriteDInt32bitArray(plcPos, writeVal, indexStart);

            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
                return result;
            }
        }


        /// <summary>
        /// 切换晶棒编号信号给1,完成之后给0
        /// </summary>
        /// <returns></returns>
        internal DataResult SwitchCrystalSignal()
        {
            string plcPos = "D80";
            ushort plcVal = 1;
            DataResult result = new DataResult();
            try
            {
                //OperateResult resOp = NetClient.Write(plcPos, plcVal);
                //if (!resOp.IsSuccess)
                //{
                //    result.Message = result.Message;
                //}
                //else
                //{
                //    result.State = true;
                //}
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
                return result;
            }
            return result;
        }

        /// <summary>
        /// 切换晶棒完成信号
        /// </summary>
        /// <returns></returns>
        internal DataResult SwitchCrystalFinish()
        {
            string plcPos = "D80";
            ushort plcVal = 0;
            DataResult result = new DataResult();
            try
            {
                //OperateResult resOp = NetClient.Write(plcPos, plcVal);
                //if (!resOp.IsSuccess)
                //{
                //    result.Message = result.Message;
                //}
                //else
                //{
                //    result.State = true;
                //}
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
                return result;
            }
            return result;
        }

        /// <summary>
        /// 获取标定板状态
        /// </summary>
        /// <returns></returns>
        internal DataResult<ushort> GetCalBoardState()
        {
            string plcPos = "D81";
            DataResult<ushort> result = new DataResult<ushort>();
            try
            {
                //ushort res = NetClient.ReadUInt16(plcPos).Content;
                //result.Data = res;
                //result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 获取PLC的数据统计,主要有三个值,一个总流入,一个是总流出,一个是当前晶棒流入,当前晶棒直流片数
        /// </summary>
        /// <returns></returns>
        internal DataResult<List<int>> GetTotalWaferCountFromPlc()
        {
            string plcRealCount = "D51"; // 工单生产实际片数
            string plcPosIn = "D21"; // 入料总数
            string plcPosOut = "D31"; // 出料总数

            string capacityPos = "D112"; // 产能
            string beatPos = "D110"; // 节拍

            DataResult<List<int>> result = new DataResult<List<int>>();
            List<int> total = new List<int>();
            try
            {
                //int res = NetClient.ReadInt32(plcRealCount).Content;
                //total.Add(res);
                //res = NetClient.ReadInt32(plcPosIn).Content;
                //total.Add(res);
                //res = NetClient.ReadInt32(plcPosOut).Content;
                //total.Add(res);


                //float res2 = NetClient.ReadFloat(capacityPos).Content;
                //res = Convert.ToInt32(res2);
                //total.Add(res); // 产能
                //res2 = NetClient.ReadFloat(beatPos).Content * 1000;
                //res = Convert.ToInt32(res2);
                //total.Add(res); // 节拍

                //result.Data = total;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }


        /// <summary>
        /// 获取PLC的运行状态和上料状态
        /// 运行: D3  1: 自动运行 2:正常停机
        /// 上料: D6  1: 上料运行, 0: 上料停止
        /// </summary>
        /// <returns></returns>
        internal DataResult<List<int>> GetPlcState()
        {
            string plcMainLinePos = "D3"; // 主线状态
            string plcLoadPos = "D6";
            DataResult<List<int>> result = new DataResult<List<int>>();
            List<int> total = new List<int>();
            try
            {
                //int res = NetClient.ReadInt32(plcMainLinePos).Content;
                //total.Add(res);
                //res = NetClient.ReadInt32(plcLoadPos).Content;
                //total.Add(res);
                //result.Data = total;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }


        /// <summary>
        /// PLC总流入和总流出重置
        /// </summary>
        /// <returns></returns>
        public DataResult ResetTotalWaferCountFromPlc()
        {
            string plcPosInReset = "D20";
            string plcPosOutReset = "D30";
            ushort resetVal = 1;

            DataResult result = new DataResult();
            try
            {
                //OperateResult resOp = NetClient.Write(plcPosInReset, resetVal);
                //resOp = NetClient.Write(plcPosOutReset, resetVal);
                //if (!resOp.IsSuccess)
                //{
                //    result.Message = result.Message;
                //}
                //else
                //{
                //    result.State = true;
                //}
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// 切换工单的时候要重置流水号和实际流入片数,还有本单直流片数
        ///  
        /// </summary>
        /// <returns></returns>
        public DataResult ResetWaferIdAndRealCount()
        {
            string waferIdReset = "D40";
            string realCountReset = "D50";
            string directionCount = "D90";
            ushort resetVal = 1;
            DataResult result = new DataResult();
            try
            {
                //OperateResult resOp = NetClient.Write(waferIdReset, resetVal);
                //resOp = NetClient.Write(realCountReset, resetVal);
                //resOp = NetClient.Write(directionCount, resetVal);
                //if (!resOp.IsSuccess)
                //{
                //    result.Message = result.Message;
                //}
                //else
                //{
                //    result.State = true;
                //}
            }
            catch (Exception ex)
            {
                result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            }
            return result;
        }

        /// <summary>
        /// Plc主线控制  D4 
        /// 1: 运行
        /// 2: 停止
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        internal DataResult PlcMainLineControl(string command)
        {
            DataResult result = new DataResult();
            //string plcPos = "D4"; // 控制主线设备
            //ushort plcVal = 0;
            //if (command.Equals("mainRun"))
            //{
            //    plcVal = 1;
            //}
            //else if (command.Equals("mainStop"))
            //{
            //    plcVal = 2;
            //}
            //try
            //{
            //    OperateResult resOp = NetClient.Write(plcPos, plcVal);
            //    if (!resOp.IsSuccess)
            //    {
            //        result.Message = result.Message;
            //    }
            //    else
            //    {
            //        result.State = true;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            //}
            return result;
        }


        /// <summary>
        /// CV 皮带清洗
        /// 位置: D7
        /// 值: 1  启动
        /// 值: 0 停止
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        internal DataResult PlcBeltClear(string command)
        {
            DataResult result = new DataResult();
            //string plcPos = "D7"; // 控制主线设备
            //ushort plcVal = 0;
            //if (command.Equals("cvRun"))
            //{
            //    plcVal = 1;
            //}
            //else if (command.Equals("cvStop"))
            //{
            //    plcVal = 0;
            //}
            //try
            //{
            //    OperateResult resOp = NetClient.Write(plcPos, plcVal);
            //    if (!resOp.IsSuccess)
            //    {
            //        result.Message = result.Message;
            //    }
            //    else
            //    {
            //        result.State = true;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            //}
            return result;
        }

        /// <summary>
        /// 上料开关控制
        /// </summary>
        /// <param name="command"></param>
        /// <returns></returns>
        internal DataResult PlcLoadControl(string command)
        {
            DataResult result = new DataResult();
            string plcPos = "D5"; // 控制上料
            ushort plcVal = 0;
            if (command.Equals("Close"))
            {
                plcVal = 2;
            }
            else if (command.Equals("Open"))
            {
                plcVal = 1;
            }
            //try
            //{
            //    OperateResult resOp = NetClient.Write(plcPos, plcVal);
            //    if (!resOp.IsSuccess)
            //    {
            //        result.Message = result.Message;
            //    }
            //    else
            //    {
            //        result.State = true;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            //}
            return result;
        }

        /// <summary>
        /// 将视觉异常写入到Plc,每次出现异常就要写入一次.
        /// </summary>
        /// <param name="plcErrorVal"></param>
        /// <returns></returns>
        internal DataResult WriteVisionErrorToPlc(ushort plcErrorVal)
        {
            DataResult result = new DataResult();
            //string plcPos = "D100"; // 视觉异常写入地址.
            //ushort plcVal = plcErrorVal;
            //try
            //{
            //    OperateResult resOp = NetClient.Write(plcPos, plcVal);
            //    if (!resOp.IsSuccess)
            //    {
            //        result.Message = result.Message;
            //    }
            //    else
            //    {
            //        result.State = true;
            //    }
            //}
            //catch (Exception ex)
            //{
            //    result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            //}
            return result;
        }


        /// <summary>
        /// 获取Plc底层的报警信息
        /// </summary>
        /// <returns></returns>
        internal DataResult<bool[]> GetPlcAlarmCode()
        {
            DataResult<bool[]> result = new DataResult<bool[]>();
            //string startPos = "W0";
            //ushort Count = 584;
            //try
            //{
            //    OperateResult<bool[]> resOp = NetClient.ReadBool(startPos, Count);
            //    if (!resOp.IsSuccess)
            //    {
            //        result.Message = result.Message;
            //    }
            //    else
            //    {
            //        result.State = true;
            //        result.Data = resOp.Content.Skip(100).Take(484).ToArray();
            //    }
            //}
            //catch (Exception ex)
            //{
            //    result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
            //}
            return result;
        }

        //internal DataResult<bool[]> GetBoxIsOkState()
        //{
        //    DataResult<bool[]> result = new DataResult<bool[]>();
        //    string startPos = "W0";
        //    ushort Count = 100;
        //    try
        //    {
        //        OperateResult<bool[]> resOp = NetClient.ReadBool(startPos, Count);
        //        if (!resOp.IsSuccess)
        //        {
        //            result.Message = result.Message;
        //        }
        //        else
        //        {
        //            result.State = true;
        //            result.Data = resOp.Content.Skip(80).Take(18).ToArray();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        result.Message = ExceptionHelper.GetFullException(ex, MethodBase.GetCurrentMethod()!);
        //    }
        //    return result;
        //}


        /// <summary>
        /// PLC数据类型bool C# bool
        /// </summary>
        /// <param name="varName"></param>
        /// <returns></returns>
        public DataResult<bool> ReadBool(string varName)
        {
            DataResult<bool> result = new DataResult<bool>();
            try
            {
                var handle = NetClient.CreateVariableHandle(varName);
                var value = (bool)NetClient.ReadAny(handle, typeof(bool));
                result.Data = value;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }


        /// <summary>
        /// PLC数据类型Byte(8bit) C# byte
        /// </summary>
        /// <param name="varName"></param>
        /// <returns></returns>
        public DataResult<byte> ReadByte(string varName)
        {
            DataResult<byte> result = new DataResult<byte>();
            try
            {
                var handle = NetClient.CreateVariableHandle(varName);
                var value = (byte)NetClient.ReadAny(handle, typeof(byte));
                result.Data = value;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// PLC数据类型SINT(8-bit)  C# sbyte
        /// </summary>
        /// <param name="varName"></param>
        /// <returns></returns>
        public DataResult<sbyte> ReadSInt8Bit(string varName)
        {
            DataResult<sbyte> result = new DataResult<sbyte>();
            try
            {
                var handle = NetClient.CreateVariableHandle(varName);
                var value = (sbyte)NetClient.ReadAny(handle, typeof(sbyte));
                result.Data = value;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }


        /// <summary>
        /// PLC数据类型INT(16-bit)  C# Short
        /// </summary>
        /// <param name="varName"></param>
        /// <returns></returns>
        public DataResult<short> ReadInt16Bit(string varName)
        {
            DataResult<short> result = new DataResult<short>();
            try
            {
                var handle = NetClient.CreateVariableHandle(varName);
                var value = (short)NetClient.ReadAny(handle, typeof(short));
                result.Data = value;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }


        /// <summary>
        /// PLC数据类型DINT  C# int
        /// </summary>
        /// <param name="varName"></param>
        /// <returns></returns>
        public DataResult<int> ReadDInt32Bit(string varName)
        {
            DataResult<int> result = new DataResult<int>();
            uint handle = 0u;
            try
            {
                handle = NetClient.CreateVariableHandle(varName);
                var value = (int)NetClient.ReadAny(handle, typeof(int));
                result.Data = value;
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            finally
            {
                if (handle != 0u)
                {
                    NetClient.DeleteVariableHandle(handle);
                }
            }
            return result;
        }

        /// <summary>
        /// PLC数据类型DINT  C# int
        /// </summary>
        /// <param name="varName"></param>
        /// <returns></returns>
        public DataResult WriteDInt32Bit(string varName, int writeVal)
        {
            DataResult result = new DataResult();
            uint handle = 0u;
            try
            {
                handle = NetClient.CreateVariableHandle(varName);
                NetClient.WriteAny(handle, writeVal);
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            finally
            {
                if (handle != 0u)
                {
                    NetClient.DeleteVariableHandle(handle);
                }
            }
            return result;
        }


        /// <summary>
        /// PLC数据类型LINT  C# long
        /// </summary>
        /// <param name="varName"></param>
        /// <returns></returns>
        public DataResult<long> ReadLInt64Bit(string varName)
        {
            DataResult<long> result = new DataResult<long>();
            try
            {
                var handle = NetClient.CreateVariableHandle(varName);
                var value = (long)NetClient.ReadAny(handle, typeof(long));
                result.Data = value;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }


        /// <summary>
        /// PLC数据类型REAL  C# float
        /// </summary>
        /// <param name="varName"></param>
        /// <returns></returns>
        public DataResult<float> ReadReal32bit(string varName)
        {
            DataResult<float> result = new DataResult<float>();
            try
            {
                var handle = NetClient.CreateVariableHandle(varName);
                var value = (float)NetClient.ReadAny(handle, typeof(float));
                result.Data = value;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// PLC读取数据类型LReal(64bit) C# double
        /// </summary>
        /// <param name="varName"></param>
        /// <returns></returns>
        public DataResult<double> ReadLReal64bit(string varName)
        {
            DataResult<double> result = new DataResult<double>();
            try
            {
                var handle = NetClient.CreateVariableHandle(varName);
                var value = (double)NetClient.ReadAny(handle, typeof(double));
                result.Data = value;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }


        /// <summary>
        /// 读取DINT类型数组的值
        /// </summary>
        /// <returns></returns>
        public DataResult<int[]> ReadDInt32bitArray(string varName, int arrayLength)
        {
            DataResult<int[]> result = new DataResult<int[]>();
            try
            {
                var handle = NetClient.CreateVariableHandle(varName);
                int[] intArray = (int[])NetClient.ReadAny(handle, typeof(int[]), new int[] { arrayLength });
                result.Data = intArray;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }


        /// <summary>
        /// 写入DINT类型数组的值
        /// </summary>
        /// <returns></returns>
        public DataResult WriteDInt32bitArray(string varName, int[] writeData, int indexStart)
        {
            DataResult result = new DataResult();
            uint handle = 0u;
            try
            {
                string plcPos = $"{varName}[{indexStart+1}]";
                handle = NetClient.CreateVariableHandle(plcPos);
                NetClient.WriteAny(handle, writeData[1]);
                plcPos = $"{varName}[{indexStart}]";
                handle = NetClient.CreateVariableHandle(plcPos);
                NetClient.WriteAny(handle, writeData[0]);
                result.State = true;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            finally
            {
                NetClient.DeleteVariableHandle(handle);
            }
            return result;
        }


        /// <summary>
        /// 读取INT类型数组的值 C# 数据类型short
        /// </summary>
        /// <returns></returns>
        public DataResult<short[]> ReadInt16bitArray(string varName, int arrayLength)
        {
            DataResult<short[]> result = new DataResult<short[]>();
            try
            {
                var handle = NetClient.CreateVariableHandle(varName);
                short[] intArray = (short[])NetClient.ReadAny(handle, typeof(short[]), new int[] { arrayLength });
                result.Data = intArray;
            }
            catch (Exception ex)
            {
                result.Message = ex.Message;
            }
            return result;
        }

    }
}
